package com.weilele.mvvm.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import com.weilele.delegate.unsafeLazy
import com.weilele.mvvm.base.helper.*
import com.weilele.mvvm.base.helper.annotation.dealViewModelAnnotation
import com.weilele.mvvm.base.livedata.*
import com.weilele.mvvm.utils.result_contract.NavigateForResultHelper
import com.weilele.mvvm.utils.result_contract.PermissionForResultHelper

/**
 * 描述：mvvm -- 基类fragment
 * 强烈建议fragment不要使用带参数的构造函数
 * 比如旋转屏幕或者系统回收重建的时候会报错（could not find Fragment constructor）
 *
 */
abstract class MvvmFragment : Fragment(), BaseMvvmInterface {
    val navigateForResultHelper by unsafeLazy { NavigateForResultHelper(this) }
    val permissionForResultHelper by unsafeLazy { PermissionForResultHelper(this) }

    /**
     * 这个fragment的onResume()是否执行过
     */
    private var _isRunFirstVisible = false
    val isRunFirstVisible
        get() = _isRunFirstVisible

    /**
     * 给fragment添加返回监听
     */
    private val onBackPressed by unsafeLazy { onBackPressed() }

    /**
     * 保存所有的注册监听者
     */
    private val observerLiveDatas = mutableListOf<LiveDataWrap>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
        //跳转帮助，必须在onCreate注册
        navigateForResultHelper
        permissionForResultHelper
        dealViewModelAnnotation()
    }

    /**
     * 监听返回按键
     */
    open fun onBackPressed(): OnBackPressedCallback? =
        null

    /**
     * 一个简单的OnBackPressedCallback对象
     */
    inline fun backPressed(crossinline listener: Function0<Unit>) =
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                listener.invoke()
            }
        }

    /**
     * 创建view
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return defaultMvvmCreateView(inflater, container, savedInstanceState)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        onBackPressed?.let {
            appCompatActivity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, it)
        }
        getObserverLiveData()?.also {
            it.observer(viewLifecycleOwner)
            observerLiveDatas.addAll(it)
        }
        getObserverLiveDataForever()?.also {
            it.observeForever()
            observerLiveDatas.addAll(it)
        }
        getClickView()?.forEach {
            it?.setOnClickListener(this)
        }
        //这里支持覆盖设置的点击事件
        initUi(savedInstanceState)
        initData()
    }


    /**
     * 通常和viewPager搭配
     */
    open fun getTitle(): CharSequence? {
        return activity?.title
    }

    /**
     * 设置title
     */
    open fun setTitle(text: CharSequence) {
        activity?.title = text
    }

    /**
     * 设置title
     */
    open fun setTitle(text: Int) {
        activity?.setTitle(text)
    }

    override fun onResume() {
        super.onResume()
        if (!_isRunFirstVisible) {
            _isRunFirstVisible = true
            onFirstVisible()
        }
    }

    /**
     * 当fragment第一次对用户展示的时候调用
     * 结合viewPage很好用
     */
    open fun onFirstVisible() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        observerLiveDatas.removeObserver()
        onBackPressed?.remove()
    }
}